import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class ChatServer {
	public static final int LOCAL_UDP_PORT = 16403;
	public static final int PEER_UDP_PORT = 16404;
	public static final int TCP_PORT = 9800;
	public static ArrayList<MemberProfile> members;
	
	private final static int bufsize = 4092;
	private static int count = 0;

	// private static final int peerport = 5100;

	private static UdpHandler2 udphandler;

	public static void main(String[] args) {
		int port = TCP_PORT;
		ServerSocket serverSocket = null;
		Socket TCPSocket = null;
		DatagramSocket UDPSocket= null;
		members = new ArrayList<MemberProfile>();
		
		
		byte[] buf = new byte[bufsize];
		
		
		try {
			udphandler = new UdpHandler2();
			udphandler.start();

			serverSocket = new ServerSocket(TCP_PORT);
			System.out.println("Server is Ready");
			//UDPSocket = new DatagramSocket(LOCAL_UDP_PORT);
			
			while (true) {
				TCPSocket = serverSocket.accept();
				if(!UdpHandler2.arraylist.contains(TCPSocket.getInetAddress())){/////////////////////change back
					System.out.println("a client is added!!");
					UdpHandler2.arraylist.add(TCPSocket.getInetAddress());/////////////////////////change back
					DatagramPacket packet = new DatagramPacket(buf,0,buf.length, TCPSocket.getInetAddress(),UdpHandler2.PEER_UDP_PORT);
					UdpHandler2.packetlist.add(packet);
			 		//UDPSocket = new DatagramSocket(LOCAL_UDP_PORT);
					//UDPSocket.disconnect();
					System.out.println("flag");
					//UDPSocket.connect(TCPSocket.getInetAddress(), PEER_UDP_PORT);
					//UdpHandler udphandler = new UdpHandler(UDPSocket);
					//System.out.println(UDPSocket.isConnected());
					//udphandler.start();
				}
				
			}
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} finally {
			try {
				serverSocket.close();
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}
	}
}
